import React, { useState, useEffect } from 'react';
import { User, RegisterForm, UserRole } from '../../types';
import { useUsers } from '../../hooks';
import { validateEmail, validatePassword } from '../../utils';
import {
  Button,
  TextInput,
  Stack,
  Group,
  Select,
  Alert
} from '@mantine/core';
import { IconAlertCircle } from '@tabler/icons-react';

interface UserFormProps {
  user?: User | null;
  onSuccess: () => void;
  onCancel: () => void;
}

const UserForm: React.FC<UserFormProps> = ({ user, onSuccess, onCancel }) => {
  const { createUser, updateUser } = useUsers();
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const [formData, setFormData] = useState<RegisterForm & { role: UserRole }>(() => ({
    username: user?.username || '',
    email: user?.email || '',
    firstName: user?.firstName || '',
    lastName: user?.lastName || '',
    password: '',
    confirmPassword: '',
    role: user?.role || UserRole.USER,
  }));

  useEffect(() => {
    if (user) {
      setFormData({
        username: user.username,
        email: user.email,
        firstName: user.firstName,
        lastName: user.lastName,
        password: '',
        confirmPassword: '',
        role: user.role,
      });
    }
  }, [user]);

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    // 验证用户名
    if (!formData.username.trim()) {
      newErrors.username = '用户名不能为空';
    } else if (formData.username.length < 3) {
      newErrors.username = '用户名至少需要3个字符';
    }

    // 验证邮箱
    if (!formData.email.trim()) {
      newErrors.email = '邮箱不能为空';
    } else if (!validateEmail(formData.email)) {
      newErrors.email = '请输入有效的邮箱地址';
    }

    // 验证姓名
    if (!formData.firstName.trim()) {
      newErrors.firstName = '名字不能为空';
    }
    if (!formData.lastName.trim()) {
      newErrors.lastName = '姓氏不能为空';
    }

    // 验证密码（仅在创建新用户或修改密码时）
    if (!user || formData.password) {
      if (!formData.password) {
        newErrors.password = '密码不能为空';
      } else {
        const passwordValidation = validatePassword(formData.password);
        if (!passwordValidation.isValid) {
          newErrors.password = passwordValidation.errors[0];
        }
      }

      if (formData.password !== formData.confirmPassword) {
        newErrors.confirmPassword = '密码确认不匹配';
      }
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setIsLoading(true);

    try {
      if (user) {
        // 更新用户
        const updateData: Partial<User> = {
          username: formData.username,
          email: formData.email,
          firstName: formData.firstName,
          lastName: formData.lastName,
          role: formData.role,
        };

        await updateUser(user.id, updateData);
      } else {
        // 创建新用户
        await createUser(formData);
      }

      onSuccess();
    } catch (error) {
      console.error('Failed to save user:', error);
      setErrors({ submit: '保存用户失败，请重试' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleInputChange = (field: keyof typeof formData) => (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    setFormData(prev => ({
      ...prev,
      [field]: e.target.value,
    }));

    // 清除该字段的错误
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <Stack gap="md">
        {errors.submit && (
          <Alert color="red" icon={<IconAlertCircle size={16} />}>
            {errors.submit}
          </Alert>
        )}

        <Group grow>
          <TextInput
            label="名字"
            value={formData.firstName}
            onChange={handleInputChange('firstName')}
            error={errors.firstName}
            placeholder="请输入名字"
            required
          />

          <TextInput
            label="姓氏"
            value={formData.lastName}
            onChange={handleInputChange('lastName')}
            error={errors.lastName}
            placeholder="请输入姓氏"
            required
          />
        </Group>

        <TextInput
          label="用户名"
          value={formData.username}
          onChange={handleInputChange('username')}
          error={errors.username}
          placeholder="请输入用户名"
          required
        />

        <TextInput
          label="邮箱"
          type="email"
          value={formData.email}
          onChange={handleInputChange('email')}
          error={errors.email}
          placeholder="请输入邮箱地址"
          required
        />

        <Select
          label="角色"
          value={formData.role}
          onChange={(value) => {
            if (value) {
              setFormData(prev => ({ ...prev, role: value as UserRole }));
              if (errors.role) {
                setErrors(prev => {
                  const newErrors = { ...prev };
                  delete newErrors.role;
                  return newErrors;
                });
              }
            }
          }}
          data={[
            { value: UserRole.USER, label: '普通用户' },
            { value: UserRole.MODERATOR, label: '管理员' },
            { value: UserRole.ADMIN, label: '超级管理员' }
          ]}
        />

        {!user && (
          <>
            <TextInput
              label="密码"
              type="password"
              value={formData.password}
              onChange={handleInputChange('password')}
              error={errors.password}
              placeholder="请输入密码"
              description="密码至少8位，包含大小写字母和数字"
              required
            />

            <TextInput
              label="确认密码"
              type="password"
              value={formData.confirmPassword}
              onChange={handleInputChange('confirmPassword')}
              error={errors.confirmPassword}
              placeholder="请再次输入密码"
              required
            />
          </>
        )}

        {user && (
          <Alert color="blue">
            💡 提示：编辑用户时密码字段为空表示不修改密码
          </Alert>
        )}

        <Group justify="flex-end" gap="sm" pt="md">
          <Button
            variant="default"
            onClick={onCancel}
            disabled={isLoading}
          >
            取消
          </Button>
          <Button
            type="submit"
            loading={isLoading}
            disabled={isLoading}
          >
            {user ? '更新' : '创建'}
          </Button>
        </Group>
      </Stack>
    </form>
  );
};

export default UserForm;